package org.changs.nav.delegate.amap;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.domain.SimpleLocation;
import org.changs.nav.delegate.global.AmapLocationTask;
import org.changs.nav.ui.nav.BaseMapFragment;
import org.changs.nav.ui.nav.PoiListFragment;

import java.util.ArrayList;

import javax.inject.Inject;

import aplug.AppManager;
import timber.log.Timber;

/**
 * Created by yincs on 2017/10/14.
 */

public class AmapSearchHelper {

    private final AppManager mAppManager;

    private PoiSearch.Query mQuery;
    private PoiSearch mPoiSearch;
    private AmapLocationTask mAmapLocationTask;
    private MapSwitchDelegate mMapSwitchDelegate;

    @Inject
    public AmapSearchHelper(AppManager appManager, AmapLocationTask amapLocationTask, MapSwitchDelegate mapSwitchDelegate) {
        mAppManager = appManager;
        mAmapLocationTask = amapLocationTask;
        mMapSwitchDelegate = mapSwitchDelegate;
    }

    public void cancel() {
        if (mPoiSearch != null)
            mPoiSearch.setOnPoiSearchListener(EMPTYL_Listener);
    }

    public void search(String key, OnPoiSearchListener listener) {
        search(key, getCity(), null, listener);
    }

    public void search(String key, String city, LatLonPoint latLonPoint, OnPoiSearchListener listener) {
        Timber.d("search() called with: key = [" + key + "], city = [" + city + "], listener = [" + listener + "]");
        mQuery = new PoiSearch.Query(key, "01|03|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20", city);
        mQuery.setPageSize(10);
        mQuery.setPageNum(0);
        if (latLonPoint != null) {
            mQuery.setLocation(latLonPoint);
            mQuery.setDistanceSort(true);
        }

        mPoiSearch = new PoiSearch(mAppManager.getContext(), mQuery);
        mPoiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                Timber.d("onPoiSearched() called with: poiResult = [" + poiResult + "], i = [" + i + "]");
                if (poiResult == null) {
                    listener.onError(i, "查询失败");
                    return;
                } else if (poiResult.getPois().size() == 0) {
                    listener.onError(-1, "没有查询到相关信息");
                    return;
                }
                Timber.d("poiItems.size() = " + poiResult.getPois().size());
                listener.onPoiSearched(poiResult.getPois());
//                List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
//                Timber.d("suggestionCities.size() = " + suggestionCities.size());
//                if (poiItems.size() > 0) {
//                    presenter.getMvpView().startPoiListView(poiItems);
//                } else if (suggestionCities.size() != 0
//                        && mCity.equals(mPoiSearch.getQuery().getCity())) {
//                    final SuggestionCity suggestionCity = suggestionCities.get(0);
//                    searchInner(presenter, text, suggestionCity.getCityCode());
//                    presenter.getMvpView().showMessage(String.format(mContext.getString(R.string.has_switch_to),
//                            suggestionCity.getCityName()));
//                } else {
//                    presenter.getMvpView().onError(R.string.sorry_not_search_result);
//                }


            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {
            }
        });
        mPoiSearch.searchPOIAsyn();
    }

    public void search(BaseMapFragment fragment, String keyword, boolean around) {
        search(fragment, keyword, around, -1);
    }

    public void search(BaseMapFragment fragment, String keyword, boolean around, int collectId) {
        fragment.showLoading()
                .setMessage("正在搜索中")
                .cancelAction(this::cancel);

        OnPoiSearchListener searchListener = new OnPoiSearchListener() {
            @Override
            public void onPoiSearched(ArrayList<PoiItem> poiItems) {
                if (fragment.isDetached()) return;
                mMapSwitchDelegate.switch2PoiList(poiItems);

//                fragment.getFragmentManager().beginTransaction()
//                        .replace(R.id.rl_container, PoiListFragment.newInstance(poiItems))
//                        .addToBackStack(null)
//                        .commitAllowingStateLoss();
                fragment.startFragment(fragment, PoiListFragment.newInstance(poiItems, collectId));
            }

            @Override
            public void onError(int code, String msg) {
                if (fragment.isDetached()) return;
                fragment.onError(msg);
                fragment.hideLoading();
            }
        };
        if (around)
            searchAround(keyword, searchListener);
        else
            search(keyword, searchListener);
    }

    public void searchAround(String keyword, OnPoiSearchListener listener) {
        search(keyword, "", getLatLonPoint(), listener);
    }


    private String getCity() {
        SimpleLocation location = mAmapLocationTask.getLocation();
        if (location == null || location.getCity() == null) return "";
        return location.getCity();
    }

    private LatLonPoint getLatLonPoint() {
        SimpleLocation location = mAmapLocationTask.getLocation();
        if (location == null) return null;
        return new LatLonPoint(location.getLatitude(), location.getLongitude());
    }

    public interface OnPoiSearchListener {
        void onPoiSearched(ArrayList<PoiItem> poiItems);

        void onError(int code, String msg);

    }

    private static final PoiSearch.OnPoiSearchListener EMPTYL_Listener = new PoiSearch.OnPoiSearchListener() {
        @Override
        public void onPoiSearched(PoiResult poiResult, int i) {

        }

        @Override
        public void onPoiItemSearched(PoiItem poiItem, int i) {

        }
    };

}
